class Solution {
public:
    int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) {
        vector<vector<int>> pf(n, vector<int>(n));
        for (int i = 0; i < n; i++) {
            int v = 0;
            for (int j = 0; j < n - 1; j++) {
                pf[i][preferences[i][j]] = ++v;
            }
        }

        set<int> unhappys;
        for (int i = 0; i < pairs.size(); i++) {
            for (int j = 0; j < pairs.size(); j++) {
                if (i == j) continue;
                int x = pairs[i][0], y = pairs[i][1];
                int u = pairs[j][0], v = pairs[j][1];
                int xy = pf[x][y], yx = pf[y][x];
                int uv = pf[u][v], vu = pf[v][u];
                int xu = pf[x][u], ux = pf[u][x];
                int xv = pf[x][v], vx = pf[v][x];
                int yu = pf[y][u], uy = pf[u][y];
                int yv = pf[y][v], vy = pf[v][y];
                if (xu < xy && ux < uv || xv < xy && vx < vu) {
                    unhappys.insert(x);
                }
                if (yu < yx && uy < uv || yv < yx && vy < vu) {
                    unhappys.insert(y);
                }
            }
        }

        return unhappys.size();
    }
};